package com.sx.service.user;

import com.sx.basic.service.BasicService;
import com.sx.basic.service.impl.BasicServiceImpl;
import com.sx.dao.user.InviteCodeRepository;
import com.sx.entity.user.InviteCodeEntity;
import com.sx.utils.RandomUtils;
import org.springframework.stereotype.Service;

/**
 * @author AdinZ
 * @date 2020/11/18 14:25
 */
@Service
public class InviteCodeService extends BasicServiceImpl<InviteCodeRepository, InviteCodeEntity,Long>
        implements BasicService<InviteCodeEntity,Long>,IInviteCodeService{
    @Override
    public Long getUid(String code) {
        InviteCodeEntity entity = this.get(code);
        if(entity==null)return null;
        return entity.getUid();
    }

    @Override
    public InviteCodeEntity get(String code) {
        InviteCodeEntity entity= this.redisService.get(InviteCodeEntity.KEY,code);
        if(entity==null){
            entity=this.repository.getByCode(code);
            if(entity!=null)
                this.redisService.set(InviteCodeEntity.KEY,code,entity);
        }
        return entity;
    }

    @Override
    public InviteCodeEntity inviteGen(long uid) {
        InviteCodeEntity entity=new InviteCodeEntity(uid);
        int index=0;
        int length=5;
        long time=System.currentTimeMillis();
        while(true) {
            String code= RandomUtils.randomStr(length);
            InviteCodeEntity codeEntity = this.get(code);
            if(codeEntity==null){
                entity.setCode(code);
                entity.setCycle(index);
                entity.setGenTime(System.currentTimeMillis()-time);
                break;
            }
            if(index%10==0&&index>0) length++;
            index++;
        }
        this.save(entity);
        this.redisService.set(InviteCodeEntity.KEY,entity.getCode(),entity);
        return entity;
    }
}
